from django.shortcuts import render, redirect
from django.urls import reverse
from django.views.generic import View
from django.core.cache import cache
from django_redis import get_redis_connection
from goods.models import GoodsType, Goods, GoodsSKU, GoodsImage, IndexGoodsBanner, IndexPromotionBanner, IndexTypeGoodsBanner
from order.models import OrderGoods
from django.core.paginator import Paginator
# Create your views here.
class IndexView(View):
    def get(self, request):
        param = cache.get("index_page_data")
        if param is None:
            print("设置缓存")
            indexGoodsBannner = IndexGoodsBanner.objects.filter(is_delete=False).order_by("index")
            indexPromotionBanner = IndexPromotionBanner.objects.filter(is_delete=False).order_by("index")

            goodsTypes = GoodsType.objects.filter(is_delete=False)

            for goodsType in goodsTypes:
                bannars = IndexTypeGoodsBanner.objects.filter(is_delete=False, type=goodsType, display_type=1).order_by("index")
                titles = IndexTypeGoodsBanner.objects.filter(is_delete=False, type=goodsType, display_type=0).order_by("index")
                goodsType.bannars = bannars
                goodsType.titles = titles

            param = {
                "indexGoodsBannner": indexGoodsBannner,
                "indexPromotionBanner": indexPromotionBanner,
                "goodsTypes": goodsTypes
            }

            cache.set("index_page_data", param, 3600)

        user = request.user
        cart_count = 0
        if user.is_authenticated:
            conn = get_redis_connection('default')
            cart_key = 'cart_%d' % user.id
            cart_count = conn.hlen(cart_key)
        param.update(cart_count=cart_count)

        return render(request, 'index.html', param)

class GoodsDetail(View):
    ''' 商品详情视图 '''
    def get(self, request, sku_id):
        try:
            sku = GoodsSKU.objects.get(id=sku_id, is_delete=False)
            images = GoodsImage.objects.filter(sku=sku, is_delete=False)
            sku.images = images
            goodsTypes = GoodsType.objects.filter(is_delete=False)
            orderGoods = OrderGoods.objects.filter(sku=sku, is_delete=False).exclude(comment='')
            new_skus = GoodsSKU.objects.filter(is_delete=False, type=sku.type).exclude(id=sku.id).order_by('-create_time')[:2]
            same_spu_skus = GoodsSKU.objects.filter(goods=sku.goods, is_delete=False).exclude(id=sku.id)
            user = request.user
            cart_count = 0
            if user.is_authenticated:
                conn = get_redis_connection('default')
                cart_key = 'cart_%d' % user.id
                cart_count = conn.hlen(cart_key)

                # 添加用户的历史记录
                history_key = 'history_%d' % user.id
                # 移除列表中的goods_id
                conn.lrem(history_key, 0, sku.id)
                # 把goods_id插入到列表的左侧
                conn.lpush(history_key, sku.id)
                # 只保存用户最新浏览的5条信息
                conn.ltrim(history_key, 0, 4)

            context = {
                "sku": sku,
                "types": goodsTypes,
                "orderGoods": orderGoods,
                "new_skus": new_skus,
                "cart_count": cart_count,
                "same_spu_skus": same_spu_skus
            }
            return render(request, 'detail.html', context)
        except GoodsSKU.DoesNotExist:
            return redirect(reverse('goods:index'))
# list/type_id/page?sort=default
class ListView(View):
    '''  列表视图 '''
    def get(self, request, type_id, page):
        try:
            goodsTypes = GoodsType.objects.filter(is_delete=False)

            type = GoodsType.objects.get(id=type_id, is_delete=False)

            new_skus = GoodsSKU.objects.filter(is_delete=False, type=type).order_by('-create_time')[:2]

            sort = request.GET.get("sort", 'default')
            if sort == 'hot':
                goodsSku = GoodsSKU.objects.filter(is_delete=False, type=type).order_by('-sales')
            elif sort == 'price':
                goodsSku = GoodsSKU.objects.filter(is_delete=False, type=type).order_by('price')
            else:
                sort = "default"
                goodsSku = GoodsSKU.objects.filter(is_delete=False, type=type).order_by('-id')

            paginator = Paginator(goodsSku, 10)
            try:
                page = int(page)
            except Exception as e:
                page = 1
            if page > paginator.num_pages:
                page = 1
            list_page = paginator.page(page)

            # 获取5页页码
            if paginator.num_pages <= 5:
                page_nums = range(1, paginator.num_pages+1)
            elif page <= 3:
                page_nums = range(1, 6)
            elif page >= paginator.num_pages - 2:
                page_nums = range(paginator.num_pages-4, paginator.num_pages+1)
            else:
                page_nums = range(page-2, page+3)

            user = request.user
            cart_count = 0
            if user.is_authenticated:
                conn = get_redis_connection('default')
                cart_key = 'card_%d' % user.id
                cart_count = conn.hlen(cart_key)

            context = {
                "type": type,
                "types": goodsTypes,
                "list_page": list_page,
                "cart_count": cart_count,
                "new_skus": new_skus,
                "sort": sort,
                "page_nums":page_nums
            }

            return render(request, 'list.html', context)

        except GoodsType.DoesNotExist:
            return redirect(reverse('goods:index'))

from haystack.views import SearchView

class SearchView(SearchView):
    '''搜索视图'''

    def create_response(self):
        """
        Generates the actual HttpResponse to send back to the user.
        """
        context = self.get_context()

        goodsTypes = GoodsType.objects.filter(is_delete=False)

        user = self.request.user
        cart_count = 0
        if user.is_authenticated:
            conn = get_redis_connection('default')
            cart_key = 'cart_%d' % user.id
            cart_count = conn.hlen(cart_key)

        context.update(types=goodsTypes, cart_count=cart_count)

        return render(self.request, 'search.html', context)
